package com.mysiteforme.admin.controller.rfid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysiteforme.admin.entity.RfidList;
import com.mysiteforme.admin.service.rfid.RfidListService;
import com.mysiteforme.admin.util.other.LayerData;
import com.mysiteforme.admin.util.other.RestResponse;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * <p>
 * RFID表  前端控制器
 * </p>
 *
 * @author rober
 * @since 2020-07-28
 */
@Controller
@RequestMapping("/admin/rfidList")
public class RfidListController {
    private static final Logger LOGGER = LoggerFactory.getLogger(RfidListController.class);

    @Autowired
    private RfidListService rfidListService;

    @GetMapping("list")
    @SysLog("跳转RFID表列表")
    public String list(){
        return "/admin/rfidList/list";
    }
    @RequiresPermissions("rfidList:list")
    @PostMapping("list")
    @ResponseBody
    @SysLog("请求RFID表列表数据")
	public LayerData<RfidList> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, ServletRequest request) {
		Map map = WebUtils.getParametersStartingWith(request, "s_");
		LayerData<RfidList> layerData = new LayerData<>();
		EntityWrapper<RfidList> wrapper = new EntityWrapper<>();
		wrapper.eq("del_flag", false);
		if (!map.isEmpty()) {
			String rfidRfidNum = (String) map.get("rfidRfidNum");
			if (StringUtils.isNotBlank(rfidRfidNum)) {
				wrapper.like("rfid_rfid_num", rfidRfidNum);
			} else {
				map.remove("rfidRfidNum");
			}

		}
	    wrapper.orderBy("create_date", false);
		Page<RfidList> pageData = rfidListService.selectPage(new Page<>(page, limit), wrapper);
		layerData.setData(pageData.getRecords());
		layerData.setCount(pageData.getTotal());
		return layerData;
	}

    @GetMapping("add")
    @SysLog("跳转新增RFID表页面")
    public String add(){
        return "/admin/rfidList/add";
    }
    @RequiresPermissions("rfidList:add")
    @PostMapping("add")
    @SysLog("保存新增RFID表数据")
    @ResponseBody
    public RestResponse add(RfidList rfidList){
        rfidListService.insert(rfidList);
        return RestResponse.success();
    }

    @GetMapping("edit")
    @SysLog("跳转编辑RFID表页面")
    public String edit(Long id,Model model){
        RfidList rfidList = rfidListService.selectById(id);
        model.addAttribute("rfidList",rfidList);
        return "/admin/rfidList/edit";
    }
    @RequiresPermissions("rfidList:edit")
    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑RFID表数据")
    public RestResponse edit(RfidList rfidList){
        if(null == rfidList.getId() || 0 == rfidList.getId()){
            return RestResponse.failure("ID不能为空");
        }
        rfidListService.updateById(rfidList);
        return RestResponse.success();
    }
    @RequiresPermissions("rfidList:delete")
    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除RFID表数据")
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(null == id || 0 == id){
            return RestResponse.failure("ID不能为空");
        }
        RfidList rfidList = rfidListService.selectById(id);
        rfidList.setDelFlag(true);
        rfidListService.updateById(rfidList);
        return RestResponse.success();
    }
    @GetMapping("upload")
    @SysLog("跳转上传upload页面")
    public String upload(){
        return "/admin/rfidList/upload";
    }
    
    @PostMapping("uploadCSV")
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
    @ResponseBody
    @SysLog("CSV文件上传")
    public  Map<String, String> uploadExcelFile(@RequestParam("file") MultipartFile[] files,HttpServletRequest httpServletRequest) {
		Map<String, String> ret = new HashMap<String, String>(); 
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMddHHmmss" );
		Date createDate= new Date();
		String rfidState ="";
		String rfidFileName="";
		try {
				for(MultipartFile file:files){
					rfidFileName=file.getOriginalFilename();
					String[] fileNameArr = file.getOriginalFilename().split("_");
				    if (fileNameArr.length >1) {
				    	 rfidState = fileNameArr[1];
				    	 createDate= sdf.parse(fileNameArr[2] );
				    }
					//读CSV内容
					Reader reader = null;
			        reader = new InputStreamReader(file.getInputStream(), "utf-8");
			        BufferedReader br = new BufferedReader( reader);
			         String line;
			            while ((line = br.readLine()) != null) {
			                if(line!=null && line!=""){
			                	String[] arr = line.split(";");
			                	if (arr.length>3 ) {
				                	if (arr[3] != null ) {
				                		RfidList rfidList = new RfidList();
				                		rfidList.setRfidBatchNum(arr[0]);
				                		rfidList.setRfidSheet(arr[1] );
				                		rfidList.setRfidSheetId(arr[2]);
				                		rfidList.setRfidRfidNum(rfid(arr[3]));
				                		rfidList.setCreateDate(createDate);
				                		rfidList.setRfidState(rfidState);
				                		rfidList.setRfidFileName(rfidFileName);
				                	    rfidListService.insert(rfidList);
				                	}
			                	}
			                }
			            }
			            reader.close();
				}
             } catch (Exception e){
                 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                 LOGGER.error(e.getMessage());
                 System.out.println(e.getMessage());
                 // return RestResponse.failure(e.getMessage());     
              }
		ret.put("type", "success");
		ret.put("msg", "文件上传成功！");
		return ret;
    }

    

    private  static String rfid(String p) {
		String id ="";
		String rfid ="";
		if ((p.length() / 2) > 7) {
			for (int i = 0; i < p.length() / 2; i++) {
				id = p.substring(i * 2, i * 2 + 2);
				rfid = id + rfid;
			}
		}
        return rfid;
    }

}